/*
 * File:   addTaskWindow.cpp
 * Author: E084412C
 *
 * Created on 12 février 2013, 14:47
 */

#include <qt4/QtGui/qlineedit.h>

#include "addTaskWindow.h"
#include "QMessageBox"

addTaskWindow::addTaskWindow(accueil *parent) {
    widget.setupUi(this);
    
    parent_=parent;
    
    updateViewTasksList();
    
    QObject::connect(widget.addTaskBtn, SIGNAL(clicked()), this, SLOT(addTaskListener()));  
}

addTaskWindow::~addTaskWindow() {
}


void addTaskWindow::addTaskListener() {
    
    QString name = widget.taskName->text();
    
    if(name=="") {
        QMessageBox::information(this,"Erreur","Votre tache n'a pas de nom !",0,0,0);
        return;
    }
    
    QTreeWidgetItem *selectedtask = widget.treeTasks->currentItem();

    
    

    
    Task *newTask;
    if(widget.checkBoxOrdo->isChecked()) {
        newTask = new Task(name.toStdString(), true, widget.number->value());
    }
    else {
        newTask = new Task(name.toStdString(), false);
    }
    
    
    if(widget.checkBoxEcheance->isChecked()) {
        newTask->setEcheance(true);
        newTask->setDeadLine(widget.comboEcheance->currentText().toStdString());
    }
    

    if(selectedtask==NULL) {
        parent_->addTopTask(newTask);
    }
    else {
        parent_->addChildTask( selectedtask->text(0).toStdString() ,newTask);        
    }
    
    
    updateViewTasksList();

    
}


void addTaskWindow::updateViewTasksList() {
    
    int nbTasks = widget.treeTasks->topLevelItemCount();
    for (int i=0; i<nbTasks;++i)
    {     
        QTreeWidgetItem *tmpItem = widget.treeTasks->takeTopLevelItem(0);
        delete tmpItem;
    }
    

    ListOfTask *currentListOfTask = parent_->getSelectedList();
    
   
    if(currentListOfTask==NULL) {
        cout << "Pas de liste" <<endl;
        this->close();
    
        return;
    }
    
    list<Task*> listOftasks = currentListOfTask->getTasks();
    
    
    for (std::list<Task*>::iterator it = listOftasks.begin(); it != listOftasks.end(); ++it) {
            Task *tmpTask = *it;
            string name = tmpTask->getTitre(); 
        
            QTreeWidgetItem *item = new QTreeWidgetItem;
            item->setText(0,QString(name.c_str()));
            widget.treeTasks->addTopLevelItem(item);
            
            list<Task*> listOfunderTasks = tmpTask->getTasks();
            
            recTaskView(item,listOfunderTasks);
            
            
        
    }
    
}



void addTaskWindow::recTaskView(QTreeWidgetItem *item, list<Task*> listOfunderTasks) {
    
    for (std::list<Task*>::iterator its = listOfunderTasks.begin(); its != listOfunderTasks.end(); ++its) {

        Task *tmpTask2 = *its;

        string name = tmpTask2->getTitre(); 

        QTreeWidgetItem *item2 = new QTreeWidgetItem;
        item2->setText(0,QString(name.c_str()));
        item->addChild(item2);
        
        recTaskView(item2,tmpTask2->getTasks());

    }

    
}